package com.example.bootdemo.common.result;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 暂时不用，觉得并无必要，仅仅处理异常就能满足需求
 */
//@Slf4j
//@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {
    //标记名称
    public static final String RESPONSE_RESULT_ANN="RESPONSE-RESULT-ANN";
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        ServletRequestAttributes sra
                = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        //判断请求是否有包装标记
        ResponseResult responseResultANN = (ResponseResult)request.getAttribute(RESPONSE_RESULT_ANN);
        return responseResultANN == null ? false:true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter,
                                  MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
//        log.info("进入 返回体 重写格式 处理中");
        if(body instanceof ResponseResult){

        }
        if(body instanceof Exception){
//            log.info("返回至异常 做包装 处理中");
            Exception e = (Exception) body;
            return ResultBody.failure("1003","出错了","错误原因");
        }
        return ResultBody.success(body);
    }


}
